#!/bin/sh
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -z "$LMD_APPS_DIR" ]; then
   echo "Error: Env LMD_APPS_DIR is not defined."
   exit 1
else 
   echo "Env LMD_APPS_DIR: "$LMD_APPS_DIR
fi

echo "lmdprogress:2"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/koboldcpp"
mkdir -p "$CURRENT_APP_PATH"
if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/koboldcpp/env_read.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/download_utils.sh"

echo "lmdprogress:5"

function create_version_dir {
   CURRENT_APP_PATH_WITH_VER="$CURRENT_APP_PATH/v${APP_VERSION}"
   mkdir -p "$CURRENT_APP_PATH_WITH_VER"
   if [ -d "$CURRENT_APP_PATH_WITH_VER" ]; then
      echo "App with version dir: "$CURRENT_APP_PATH_WITH_VER
   else
      echo "Error, App with version dir dose not exist, please retry. "$CURRENT_APP_PATH_WITH_VER
      exit 1
   fi
}

function install_for_mac {
   INSTALLER_URL=$_MAC_DOWNLOAD_URL

   INSTALLER_FILE_PATH="$CURRENT_APP_PATH_WITH_VER/${_MAC_INSTALLER_FILE_NAME}"
   download_with_resume "$INSTALLER_FILE_PATH" $INSTALLER_URL
   echo "downloaded."
   echo "lmdprogress:90"
   chmod +x $INSTALLER_FILE_PATH
   echo "install finished."
}

install_for_win() {
  INSTALLER_FILE_PATH="$CURRENT_APP_PATH_WITH_VER/${_WINDOWS_INSTALLER_FILE_NAME}"
  INSTALLER_URL=$_WINDOWS_DOWNLOAD_URL
  if command -v nvidia-smi &> /dev/null; then
    echo "Found NVIDIA GPU."
   #  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/check_cuda_ver.sh"
   #  if [[ $CUDA_MAJOR_VERSION -eq 12 || $CUDA_MAJOR_VERSION -eq 13 ]]; then
      INSTALLER_FILE_PATH="$CURRENT_APP_PATH_WITH_VER/${_WINDOWS_INSTALLER_FILE_NAME_CU12}"
      INSTALLER_URL=$_WINDOWS_CU12_DOWNLOAD_URL
   #  fi
  else
    echo "No NVIDIA GPU"
  fi

  echo "remote url: $INSTALLER_URL"

  download_with_resume "$INSTALLER_FILE_PATH" $INSTALLER_URL
  
  echo "lmdprogress:90"
  if [ $? -eq 0 ]; then
    echo "downloaded."
  else
    echo "download error."
  fi
}


create_version_dir

echo "lmdprogress:35"

if [ -f /etc/os-release ]; then
   echo "Linux system."
   echo "Not supported."
   exit 1
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   install_for_mac
elif current_os_is_windows; then
   echo "Windows system."
   install_for_win
else
   echo "Unknown OS"
fi


echo "lmdprogress:100"